package com.fuhe.studydemo.custom;

import android.content.Context;
import android.graphics.*;
import android.util.AttributeSet;
import android.widget.RelativeLayout;

public class DrawRelativeLayout extends RelativeLayout {

    private int mType = 0;

    private Paint mPaint = new Paint();

    public DrawRelativeLayout(Context context) {
        this(context, null);
    }

    public DrawRelativeLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public DrawRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mPaint.setAntiAlias(true);//设置画笔为无锯齿
        mPaint.setDither(true);//设置画笔为防抖动
        mPaint.setColor(Color.BLACK);//设置画笔的颜色
        mPaint.setStrokeWidth(3);//设置画笔的线宽
        mPaint.setStyle(Paint.Style.STROKE);//设置画笔的类型为空心
    }

    public void setDrawType(int type) {
        //背景设置为白色,目的是把画布擦干净
        setBackgroundColor(Color.WHITE);
        mType = type;

        //立即重新绘图
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int measuredWidth = getMeasuredWidth();
        int measuredHeight = getMeasuredHeight();
        if (measuredHeight > 0 && measuredHeight > 0) {
            if (mType == 0) {
                Rect rect = new Rect(0, 0, measuredWidth, measuredHeight);
                canvas.drawRect(rect, mPaint);
            } else if (mType == 1) {
                RectF rectF = new RectF(0, 0, measuredWidth, measuredHeight);
                canvas.drawRoundRect(rectF, 30, 30, mPaint);
            } else if (mType == 2) {
                RectF rectF = new RectF(0, 0, measuredWidth, measuredHeight);
                canvas.drawOval(rectF, mPaint);
            } else if (mType == 3) {
                int radius = Math.min(measuredWidth, measuredHeight) / 2;
                canvas.drawCircle(measuredWidth / 2, measuredHeight / 2, radius, mPaint);
            } else if (mType == 4) {
                Rect rect = new Rect(0, 0, measuredWidth, measuredHeight);
                canvas.drawRect(rect, mPaint);
                canvas.drawLine(0, 0, measuredWidth, measuredHeight, mPaint);
                canvas.drawLine(0, measuredHeight, measuredWidth, 0, mPaint);
            }
        }
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        super.dispatchDraw(canvas);
        int measuredWidth = getMeasuredWidth();
        int measuredHeight = getMeasuredHeight();
        if (mType ==5) {
            Rect rect = new Rect(0, 0, measuredWidth, measuredHeight);
            canvas.drawRect(rect, mPaint);
            canvas.drawLine(0, 0, measuredWidth, measuredHeight, mPaint);
            canvas.drawLine(0, measuredHeight, measuredWidth, 0, mPaint);
        }
    }
}
